<script setup>
import { ref } from "vue";
import "@kitware/vtk.js/favicon";

// Load the rendering pieces we want to use (for both WebGL and WebGPU)
import "@kitware/vtk.js/Rendering/Profiles/Geometry";

import vtkActor from "@kitware/vtk.js/Rendering/Core/Actor";
import vtkGenericRenderWindow from "@kitware/vtk.js/Rendering/Misc/GenericRenderWindow";
import vtkMapper from "@kitware/vtk.js/Rendering/Core/Mapper";
import vtkSTLReader from "@kitware/vtk.js/IO/Geometry/STLReader";
import vtkPolyDataNormals from "@kitware/vtk.js/Filters/Core/PolyDataNormals";
// ----------------------------------------------------------------------------
// Example code
// ----------------------------------------------------------------------------

let genericRenderWindow;
let renderer;
let renderWindow;
let resetCamera;
let render;
const renderContainer = ref();
// ----------------------------------------------------------------------------
function initRender() {
  genericRenderWindow = vtkGenericRenderWindow.newInstance();
  genericRenderWindow.setContainer(renderContainer.value);
  genericRenderWindow.resize();
  renderer = genericRenderWindow.getRenderer();
  renderWindow = genericRenderWindow.getRenderWindow();
  resetCamera = renderer.resetCamera;
  render = renderWindow.render;
}

function update(reader) {
  const mapper = vtkMapper.newInstance({ scalarVisibility: false });
  const actor = vtkActor.newInstance();
  actor.setMapper(mapper);
  mapper.setInputConnection(reader.getOutputPort());
  renderer.addActor(actor);
  resetCamera();
  render();
}

// ----------------------------------------------------------------------------
// Use a file reader to load a local file
// ----------------------------------------------------------------------------

function handleFile(event) {
  event.preventDefault();
  const dataTransfer = event.dataTransfer;
  const files = event.target.files || dataTransfer.files;
  initRender();
  console.log(files);
  Array.from(files).forEach((file) => {
    const fileReader = new FileReader();
    let reader = vtkSTLReader.newInstance();
    fileReader.onload = (e) => {
      reader.parseAsArrayBuffer(fileReader.result);
      update(reader);
    };
    fileReader.readAsArrayBuffer(file);
  });
}
</script>
<template>
  <div class="mianContainer" ref="renderContainer">
    <input type="file" class="fileInput_local" @change="handleFile" multiple />
  </div>
</template>
<style lang="scss" scoped>
.mianContainer {
  width: 100%;
  height: calc(100vh - 100px);
}
</style>
